//
//  CJBnimationMainViewController.m
//  CoJellyCartoon
//
//  Created by dllo on 16/3/30.
//  Copyright © 2016年 CJG. All rights reserved.
//

#import "CJBnimationMainViewController.h"
#import "LzwBnmCollectionReusableView.h"
#import "WZAFNetTool.h"
#import "LzwBnimaLoadingCell.h"
#import "LzwBnEndTableViewCell.h"
#import "LzwBniRecommendCell.h"
#import <MJRefresh.h>
#import <MJRefreshHeader.h>
#import <MJRefreshFooter.h>
#import "LzwIndexingVC.h"
#import "LzwBroadcastVC.h"

#import "LzwBangumiDetailVC.h"

#import "LzwBnimationWebView.h"


@interface CJBnimationMainViewController ()<UITableViewDataSource, UITableViewDelegate, LzwBnmCollectionReusableViewDelegata, LzwBnimaLoadingCellDelegate, LzwBnEndTableViewCellDeleGate>

@property (nonatomic, strong) CJBaseTableView *myBnimationTableView;

//头部视图
@property (nonatomic, strong) LzwBnmCollectionReusableView *myHeaderView;

@property (nonatomic,assign) NSInteger nextPage; //记录下一页


@property (nonatomic, assign) BOOL isUpLoading;


@end

@implementation CJBnimationMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor yellowColor];
 
    ///初始化数组
    self.arrayLoad = [NSMutableArray array];
    self.arrayEnd  = [NSMutableArray array];
    self.arrayRecommend = [NSMutableArray array];
    
    //创建TableView
    [self creatCollectView];
}

- (void)creatCollectView{
    
    self.myBnimationTableView = ({

        CJBaseTableView *myTableView = [[CJBaseTableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 70) style:UITableViewStyleGrouped];
        myTableView.backgroundColor = [UIColor whiteColor];
        myTableView.delegate = self;
        myTableView.dataSource = self;
        myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [self.view addSubview:myTableView];
        
        myTableView;
    
    });

    [self.myBnimationTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    //新番连载
    [self.myBnimationTableView registerClass:[LzwBnimaLoadingCell class] forCellReuseIdentifier:@"cellLoad"];
 
    //完结动画
    [self.myBnimationTableView registerClass:[LzwBnEndTableViewCell class] forCellReuseIdentifier:@"cellEnd"];
    //推荐
    [self.myBnimationTableView registerClass:[LzwBniRecommendCell class] forCellReuseIdentifier:@"cellR"];
    
    
    //头部视图
    self.myBnimationTableView.tableHeaderView = [self creaHrader];


    
    //请求数据
    //请求数据
    //下拉刷新

    [GiFHUD show];
    [GiFHUD setGifWithImageName:@"hold.gif"];
    
    
    [self p_addHeader];
    [self p_addFooter];
    
    

}

-(LzwBnmCollectionReusableView *)creaHrader{
    
      self.myHeaderView = [[LzwBnmCollectionReusableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 160)];
    self.myHeaderView.myDelegate = self;
    
    return _myHeaderView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 1;
    }else{
        return self.arrayRecommend.count;
    }
   
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (indexPath.section == 0) {
        
        LzwBnimaLoadingCell *cellL = [tableView dequeueReusableCellWithIdentifier:@"cellLoad"];
        cellL.myDeleGate = self;
        cellL.arrayAll = self.arrayLoad;
        
        return cellL;
    }else if (indexPath.section == 1){
        
        LzwBnEndTableViewCell *cellE = [tableView dequeueReusableCellWithIdentifier:@"cellEnd"];
        cellE.myDeleGate = self;
        cellE.arrayEnd = self.arrayEnd;
        
        return cellE;
    }else{
        
        LzwBniRecommendCell *cellR = [tableView dequeueReusableCellWithIdentifier:@"cellR"];
        cellR.modleR = _arrayRecommend[indexPath.row];
        return cellR;
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        return 700;
    }else if (indexPath.section == 1){
        return 270;
    }

    LzwBniRecomModle *model = _arrayRecommend[indexPath.row];
        return  model.sizeFontHeiget + 170;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LzwBniRecomModle *model = _arrayRecommend[indexPath.row];
    
    LzwBangumiDetailVC *detailVc = [[LzwBangumiDetailVC alloc]init];
    
    if ([model.link containsString:@"html"]) {

        LzwBnimationWebView *webView = [[LzwBnimationWebView alloc]init];
        
        webView.webViewUrl = model.link;
        webView.title = model.title;
        [self.navigationController pushViewController:webView animated:YES];
        
    }
else{
 
    
    
    NSString *str = model.link;
    NSString *string = [str substringFromIndex:34];
    //34
    //(@"----- = %@", string);
    
    if ([str containsString:@"category"]) {
        [self alertStates:@"提示" Message:@"暂时没有开放" Action:@"确定"];
        return;
        
    }else{
    
    detailVc.ting_ID = string.intValue;
    
    [self.navigationController pushViewController:detailVc animated:YES];
        
    }
      }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 2) {
    
        UIView *myview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
        myview.backgroundColor = [UIColor whiteColor];
        
        UILabel *lableT = [[UILabel alloc]initWithFrame:CGRectMake(50, 15, 150, 20)];
        lableT.text = @"番剧推荐";
        lableT.textColor = [UIColor lightGrayColor];
        [myview addSubview:lableT];
        
        UIImageView *imagViewL = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 30, 30)];
        imagViewL.image = [UIImage imageNamed:@"L5.png"];
        imagViewL.layer.masksToBounds = YES;
        imagViewL.layer.cornerRadius = 15;
        [myview addSubview:imagViewL];
        return myview;
    }else{
        return nil;
 
    }

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    if (section == 2) {
        return @"番剧推荐";
    }else{
        
        return nil;
    }
    
    
}


- (void)getHeaderData{
    
    NSString *url = @"http://bangumi.bilibili.com/api/app_index_page_v2?_device=android&_hwid=e647d7e136a2c2a9&_ulv=10000&access_key=ac2771d488a63b7c3f8ccf926d8fe761&appkey=c1b107428d337928&build=414000&platform=android&ts=1459331038000&sign=10781fa9308c34870235f41b5b6cf643";
    
    //(@"vvvvvv = %@", url);
    
    [WZAFNetTool GetNetWithURL:url WithBody:nil headfile:nil response:WZJSON success:^(id reuslt) {
       
        NSMutableDictionary *dict = [reuslt objectForKey:@"result"];
//        
#pragma mark -- 新番连载
        NSMutableDictionary *diction = [dict objectForKey:@"latestUpdate"];
        
        
        NSMutableArray *arrayLoad = [diction objectForKey:@"list"];
        
        for (NSMutableDictionary *dictL in arrayLoad) {
      
            LzwLatesModel *latesM = [[LzwLatesModel alloc]init];
            
            [latesM setValuesForKeysWithDictionary:dictL];
            
            [self.arrayLoad addObject:latesM];
            
        }
#pragma mark -- 完结动画
        NSMutableArray *arrayEnd = [dict objectForKey:@"ends"];
        
        for (NSMutableDictionary *dictE in arrayEnd) {
            
            LzwLatesModel *latesM1 = [[LzwLatesModel alloc]init];
            
            [latesM1 setValuesForKeysWithDictionary:dictE];
            
            [self.arrayEnd addObject:latesM1];
        }
        
        [self.myBnimationTableView.mj_header endRefreshing];
        [self.myBnimationTableView reloadData];
        
        [GiFHUD dismiss];
        
    } failure:^(NSError *error) {
        
        
    }];
    
}


-(void)getRecommend:(NSInteger)pageSize{
    
    NSString *url = [NSString stringWithFormat:@"http://bangumi.bilibili.com/api/bangumi_recommend?_device=android&_hwid=e647d7e136a2c2a9&appkey=c1b107428d337928&build=414000&cursor=-1&pagesize=%@&platform=android&ts=1459331038000&sign=9ec86d16473785b66a0082611de7b2e9", [NSString stringWithFormat:@"%ld", pageSize]];
    
    
    //(@"了 = %@", url);
    
    
    [WZAFNetTool GetNetWithURL:url WithBody:nil headfile:nil response:WZJSON success:^(id reuslt) {
        
        NSMutableArray *arrayR = [reuslt objectForKey:@"result"];
#pragma mark -- 推荐
        for (NSMutableDictionary *dict in arrayR) {
            
            LzwBniRecomModle *modleR = [[LzwBniRecomModle alloc]init];
            
            [modleR setValuesForKeysWithDictionary:dict];
            
            [self.arrayRecommend addObject:modleR];
        }
 
        [self.myBnimationTableView.mj_footer endRefreshing];
        [self.myBnimationTableView reloadData];
    } failure:^(NSError *error) {
        
        
    }];
    
}

- (void)p_addHeader{
    
//    
//   self.myBnimationTableView.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
//
//       [self getHeaderData];
//       
//   }];
//    
//    [self.myBnimationTableView.mj_header beginRefreshing];
    
//    __weak CJBnimationMainViewController *LzwVc = self;
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.nextPage = 0;
        [self getHeaderData];
        
//        [LzwVc.myBnimationTableView.mj_header endRefreshing];
    }];
    
    self.myBnimationTableView.mj_header = header;
    [self.myBnimationTableView.mj_header beginRefreshing];
    
    [header setTitle:@"正在刷新" forState:MJRefreshStateRefreshing];
    
    
    

}
//上拉和下拉是2个接口,分别请求数据
#pragma mark - 上拉刷新
- (void)p_addFooter{


    __weak CJBnimationMainViewController *BnimaVc = self;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
       
        self.nextPage += 10;
        
        [BnimaVc getRecommend:self.nextPage];
        
        [BnimaVc.myBnimationTableView.mj_footer beginRefreshing];
        
    }];
    //空闲状态
    [footer setTitle:@"空闲状态" forState:MJRefreshStateIdle];
    //正在刷新状态
    [footer setTitle:@"正在刷新状态 ..." forState:MJRefreshStateRefreshing];
    //没有跟多数据
    [footer setTitle:@"没有跟多数据" forState:MJRefreshStateNoMoreData];
//    footer.stateLabel.textColor = kAppearanceColor;
    self.myBnimationTableView.mj_footer = footer;
    
    [BnimaVc.myBnimationTableView.mj_footer beginRefreshing];

    
    
}


//headerbutton点击方法
///放送表
-(void)broadcastButtonAction{
    
    //(@"来了");
    LzwBroadcastVC *broadVc = [[LzwBroadcastVC alloc]init];
    
    [self.navigationController pushViewController:broadVc animated:YES];
}
///索引
-(void)searchButtonAction{
    //(@"都一样");
    LzwIndexingVC *indexVc = [[LzwIndexingVC alloc]init];
    
    [self.navigationController pushViewController:indexVc animated:YES];
}


//新番连载协议
//- (void)bnimalLoadingCellAction:(NSInteger)indexPath{
//    
//    LzwBangumiDetailVC *detailVc = [[LzwBangumiDetailVC alloc]init];
//    
//    detailVc.ting_ID = indexPath;
//    
//    [self.navigationController pushViewController:detailVc animated:YES];
//    
//}

-(void)bnimalLoadingCellAction:(NSInteger)indexPath oldID:(NSInteger)oldID{
    
    LzwBangumiDetailVC *detailVc = [[LzwBangumiDetailVC alloc]init];
    
    detailVc.ting_ID = indexPath;
    detailVc.oldID = oldID;
    [self.navigationController pushViewController:detailVc animated:YES];
    
    
}

//- (void)bnimalLoadPLcell:(NSInteger)oldID{
//    
//    LzwBangumiDetailVC *detailVc = [[LzwBangumiDetailVC alloc]init];
//    
//    detailVc.oldID = oldID;
//    
//    [self.navigationController pushViewController:detailVc animated:YES];
//    
//    
//}


///完结动画
-(void)pushNextPage:(NSString *)seaon_id{
    
    LzwBangumiDetailVC *detailVc = [[LzwBangumiDetailVC alloc]init];
    
    detailVc.ting_ID = seaon_id.intValue;
    
    [self.navigationController pushViewController:detailVc animated:YES];
    
}



- (void)alertStates:(NSString *)title Message:(NSString *)message Action:(NSString *)action{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    [self presentViewController:alert animated:YES completion:^{
        
        
    }];
    
    UIAlertAction *actionT = [UIAlertAction actionWithTitle:action style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    [alert addAction:actionT];
}


@end
